﻿using Payroll.Biz.Legacy.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Payroll.Biz.Legacy.Models
{
    public class UnionAffiliation : IAffiliation
    {
        public Guid MemberId { get; private set; }

        public decimal Dues { get; private set; }

        public Dictionary<DateTime, ServiceCharge> Charges { get; private set; }

        public UnionAffiliation(Guid memberId, decimal dues)
        {
            MemberId = memberId;
            Dues = dues;
            Charges = new Dictionary<DateTime, ServiceCharge>();
        }

        public void AddServiceCharge(ServiceCharge serviceCharge)
        {
            Charges.Add(serviceCharge.Time, serviceCharge);
        }

        public ServiceCharge GetServiceCharge(DateTime time)
        {
            return Charges[time];
        }

        public decimal CalculateDeductions(Paycheck paycheck)
        {
            decimal result = 0m;

            int fridays = DateUtils.NumberOfFridaysInDayPeriod(paycheck.PayPeriodStartDate, paycheck.PayPeriodEndDate);
            result = Dues * fridays;

#pragma warning disable S3267 // Loops should be simplified with "LINQ" expressions
            foreach (ServiceCharge charge in Charges.Values)
            {
                if (DateUtils.IsInPayPeriod(charge.Time, paycheck.PayPeriodStartDate, paycheck.PayPeriodEndDate))
                {
                    result += charge.Amount;
                }
            }
#pragma warning restore S3267 // Loops should be simplified with "LINQ" expressions

            return result;
        }

        public override string ToString()
        {
            return $"{{{nameof(MemberId)}={MemberId.ToString()}, {nameof(Dues)}={Dues.ToString()}, {nameof(Charges)}={Charges}}}";
        }

        public override bool Equals(object obj)
        {
            return (obj is UnionAffiliation affiliation) &&
                MemberId.Equals(affiliation.MemberId) &&
                (Dues == affiliation.Dues);
        }

        public override int GetHashCode()
        {
            int hashCode = -897566634;
            hashCode = (hashCode * (-1521134295)) + MemberId.GetHashCode();
            hashCode = (hashCode * (-1521134295)) + Dues.GetHashCode();
            return hashCode;
        }
    }
}
